package com.dc.web.controller;


import com.dc.dao.ConfigDao;
import com.dc.entity.ConfigEntity;
import com.dc.model.AjaxResult;
import com.dc.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/config")
@Slf4j
public class ConfigController {

    @Resource
    ConfigDao configDao;

    @GetMapping("/list")
    public AjaxResult list() {
        List<ConfigEntity> all = configDao.findAll();
        return AjaxResult.success(all);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<ConfigEntity> optional = configDao.findById(id);

        ConfigEntity configEntity = null;

        if(optional.isPresent()) {
            configEntity = optional.get();
        }

        return AjaxResult.success(configEntity);
    }

    @PostMapping()
    public AjaxResult add(@RequestBody ConfigEntity entity) {

        entity.setId(null);
        ConfigEntity config = configDao.findByYearAndName(entity.getYear(), entity.getName());
        if(config != null) {
            config.setValue(entity.getValue());
            configDao.save(config);
            return AjaxResult.success(config);
        }
        ConfigEntity save = configDao.save(entity);
        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody ConfigEntity entity) {

        entity.setId(id);
        ConfigEntity save = configDao.save(entity);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        configDao.deleteById(id);

        return AjaxResult.success();
    }

    @PostMapping("/extend/lastyear")
    public AjaxResult extendsConfigFromLastYear() {
        Integer year = DateUtils.getYear();
        int lastYear = year - 1;
        List<ConfigEntity> configEntityList = configDao.findByYear(lastYear);
        if(ObjectUtils.isEmpty(configEntityList)) {
            return AjaxResult.error("上一年度没有配置数据");
        }
        configDao.deleteByYear(year);

        List<ConfigEntity> result = new ArrayList<>();
        for(ConfigEntity configEntity : configEntityList) {
            ConfigEntity tmp = new ConfigEntity();
            tmp.setYear(year);
            tmp.setName(configEntity.getName());
            tmp.setValue(configEntity.getValue());
            result.add(tmp);
        }

        List<ConfigEntity> configEntities = configDao.saveAll(result);

        return AjaxResult.success(result);
    }
}
